package com.lanhai.common.phantomjs;
import com.lanhai.common.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.*;

enum exportTypeEnum{
    PDF,
    PNG,
    JPEG,
    BMP
}

/**
 * 将指定网页内容输出为指定格式
 * 依赖phantomjs环境
 */
@Slf4j
public class RenderPage {

    //TODO:需设将phantomjs设置到环境变量
    private static String exePath="./phantomjs";
    private static String jsPath=Thread.currentThread().getContextClassLoader().getResource("").getPath()+"scripts/rasterize.js";
    //

    public static void main(String[] args) throws IOException {
        new RenderPage().exportPage("http://120.27.17.206:8000/qrcode/userlist?ids=120176175841542144&count=78",1,"/Users/ianzhang/Downloads/");
    }

    /***
     *将指定网页导出为指定图片或pdf
     * @param url
     * @param exportType
     * @param destination 目的地址
     * @return
     * @throws IOException
     */
    public String exportPage(String url,int exportType,String destination){
        String fileName=IdUtil.getUUID();

        try {
            switch (exportTypeEnum.values()[exportType])
            {
                case PDF:
                    fileName+=".pdf";
                    break;
                case BMP:
                    fileName+=".bmp";
                    break;
                case PNG:
                    fileName+=".png";
                    break;
                case JPEG:
                    fileName+=".jpeg";
                    break;
            }
        }
        catch (Exception e){
            log.error(e.getMessage());
        }
        //
        Runtime rt = Runtime.getRuntime();
        try {
            File f = new File(this.getClass().getResource("/scripts/rasterize.js").getPath());
            String JSPath=f.getAbsolutePath();
            exePath="/usr/share/phantomjs";
            //
            rt.exec(exePath + " " + JSPath+" "+url+" "+destination+ fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return fileName;
    }
}
